package com.example.t470p.facechecktickets;
/**
 * 新中新手持机二代证指纹开发例程
 * 添加连续读卡  时间和次数统计    添加读卡超时进入休眠的功能
 * 有指纹扫描和显示功能
 */

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;


import com.example.t470p.facechecktickets.Utils.signUtils;
import com.example.t470p.facechecktickets.Utils.xmlUtil;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;


public class MainActivity extends Activity {
    private EditText m_userName;
    private EditText m_passWord;


    public String m_strUserName;
    public String m_strPassWord;
    public String m_Url;
    public String m_strGateNo;
    //添加sharePreferce用于保存密码和登录
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;
    private CheckBox rememberPass;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //取消标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //取消状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);

        m_userName = (EditText) findViewById(R.id.userName);
        m_passWord = (EditText) findViewById(R.id.passWord);

        String ConfigPath = getSDPath() + "/config.ini";
        GetConfig(ConfigPath);

        pref = PreferenceManager.getDefaultSharedPreferences(this);

        rememberPass = (CheckBox) findViewById(R.id.remember_pass);

        boolean isRemember = pref.getBoolean("remember_password", false);
        if (isRemember) {
            // 将账号和密码都设置到文本框中
            String m_strUserName = pref.getString("account", "");
            String m_strPassWord = pref.getString("password", "");
            m_userName.setText(m_strUserName);
            m_passWord.setText(m_strPassWord);
            rememberPass.setChecked(true);
        } else {
            m_passWord.setText("");
        }


    }

    /*
     * 获取SD卡路径
     */
    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }

    /*
     * 获取配置信息
     */
    public boolean GetConfig(String ConfigPath) {
        boolean ret = false;
        try {
            FileInputStream fis = null; // 读
            Properties pp;

            pp = new Properties();
            fis = new FileInputStream(ConfigPath);
            pp.load(fis);

            m_Url = pp.get("SericeUrl").toString();

            m_strGateNo = pp.get("GateNO").toString();// 获取配置文件的Gps_device字段的信息，既它=号后面的数据

            m_strUserName = pp.get("UserName").toString();

            m_strPassWord = pp.get("PassWord").toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    /*
     * 登录按钮点击事件
     */
    public void BtnLogInOnClick(View v) {

        //登录按钮
        m_strUserName = m_userName.getText().toString();
        m_strPassWord = m_passWord.getText().toString();

        if (m_Url == null || m_Url.equals("")) {
            showToast("请配置URL");
            return;
        }
        if (m_strUserName == null || m_strUserName.equals("")) {
            showToast("请输入用户名");
            return;
        }
        if (m_strPassWord == null || m_strPassWord.equals("")) {
            showToast("请输入密码");
            return;
        }
        if (m_strGateNo == null || m_strGateNo.equals("")) {
            HttpURL();
        } else {
            new AlertDialog.Builder(MainActivity.this).setTitle("绑定手持机终端").setMessage("是否取消绑定？")
                    .setPositiveButton("是", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            HttpURLRelese();
                        }
                    })
                    .setNegativeButton("否", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            //提示是否取消绑定
                            HttpURL();
                        }
                    })
                    .show();
        }
    }

    /*
     * http请求
     */
    private void HttpURL() {
        new Thread() {
            public void run() {
                send();
            }
        }.start();
    }

    /*
     * 发送Http请求
     */
    public boolean send() {
        try {

            Map<String, String> map = new HashMap<String, String>();
            map.put("userName", m_strUserName);
            map.put("password", m_strPassWord);
            String sign = signUtils.buildMysign(map, "zmdjfkgudjrhkhssnh");
            System.out.println(sign);

            //String sendDate = "userName=admin" + "&password=admin" + "&sign=" + sign;
            String sendDate = "userName=" + m_strUserName + "&password=" + m_strPassWord + "&sign=" + sign;

            String result = httpUtils.sendPost(BaseUrl.userLogin, sendDate);
            System.out.println(result);
            //是否登录成功
            if (result.indexOf("<code>0</code>") > 0) {
                //使用sharePreference保存密码，登录信息
                editor = pref.edit();
                if (rememberPass.isChecked()) {
                    editor.putBoolean("remember_password", true);
                    editor.putString("account", m_strUserName);
                    editor.putString("password", m_strPassWord);
                } else {
//					editor.clear();
                    editor.putBoolean("remember_password", false);
                    editor.putString("password", "");
                }
                editor.commit();

                if (m_strGateNo == null || m_strGateNo.equals("")) {
                    Intent intent = new Intent(MainActivity.this, SelectGateActivity.class);
                    Bundle bundle = new Bundle();
                    /*字符、字符串、布尔、字节数组、浮点数等等，都可以传*/
                    bundle.putString("url", m_Url);
                    bundle.putString("myname", m_strUserName);
                    bundle.putString("mypwd", m_strPassWord);
                    /*把bundle对象assign给Intent*/
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else {
                    //提示是否取消绑定
                    Intent intent = new Intent(MainActivity.this, CheckActivity.class);
                    startActivity(intent);
                }
                finish();
            } else {
                //提示
                String msg = xmlUtil.getxmlstr(result, "message");
                System.out.println("test:" + msg);
                showToast(msg);
            }
        } catch (Exception e) {
            showToast("请检查地址配置！"+e.toString());
            return false;
        }
        return true;
    }

    /*
     * Relese Http请求
     */
    private void HttpURLRelese() {
        new Thread() {
            public void run() {
                sendRelese();
            }
        }.start();

    }

    /*
     * 发送Relese Http请求
     */
    public boolean sendRelese() {
        try {

            Map<String, String> map = new HashMap<String, String>();
/*			map.put("userName", m_strUserName);
			map.put("password", m_strPassWord);*/
            map.put("gateNo", m_strGateNo);
            String sign = signUtils.buildMysign(map, "zmdjfkgudjrhkhssnh");
            System.out.println(sign);

            //String sendDate = "userName=admin" + "&password=admin" + "&sign=" + sign;"userName="+ m_strUserName + "&password=" + m_strPassWord +
            String sendDate = "gateNo=" + m_strGateNo + "&sign=" + sign;
            String result = httpUtils.sendPost(BaseUrl.gateReleseBound, sendDate);
            System.out.println(result);

            if (result.indexOf("<code>0</code>") > 0) {

                m_strGateNo = "";
                HttpURL();
                showToast("取消绑定成功！");

            } else {
                String msg = xmlUtil.getxmlstr(result, "message");
                System.out.println("test:" + msg);
                showToast(msg);
            }
        } catch (Exception e) {
            showToast("请检查地址配置！");
            return false;
        }
        return true;
    }


    //非UI线程中显示Toast
    public void showToast(String msg) {
        Looper.prepare();
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
        Looper.loop();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
